<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 角色列表区域 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-button @click="addRolesDialogVisible = true" type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-row>
        <el-table :data="rolesList" border stripe style="width: 100%">
          <el-table-column type="expand" label="展开">
            <!-- 权限列表区域 -->
            <template slot-scope="scope">
              <el-row
                :class="['bdBottom', index1 === 0? 'bdTop':'', 'vcenter']"
                v-for="(item1, index1) in scope.row.children"
                :key="item1.id"
                :gutter="20"
              >
                <!-- 一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close="removeRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 二级权限和三级权限区域 -->
                <el-col :span="19">
                  <!-- 渲染二级权限 -->
                  <el-row
                    :class="[index2 === 0? '':'bdTop', 'vcenter']"
                    v-for="(item2, index2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        closable
                        type="success"
                        @close="removeRightsById(scope.row, item2.id)"
                      >{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染三级权限 -->
                    <el-col :span="18">
                      <el-tag
                        @close="removeRightsById(scope.row, item3.id)"
                        v-for="(item3) in item2.children"
                        :key="item3.id"
                        type="warning"
                        closable
                      >{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="编号"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"></el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                @click="showEditRolesDialog(scope.row)"
                size="mini"
                type="primary"
                icon="el-icon-edit"
              >编辑</el-button>
              <el-button
                @click="removeRole(scope.row.id)"
                size="mini"
                type="danger"
                icon="el-icon-delete"
              >删除</el-button>
              <el-button
                @click="showRightsDialogVisible(scope.row)"
                size="mini"
                type="warning"
                icon="el-icon-setting"
              >分配权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>

    <!-- 分配权限对话框 -->
    <template>
      <el-dialog
        @close="setRightsDialogClear"
        title="分配权限"
        :visible.sync="setRightsDialogVisible"
        width="50%"
      >
        <el-tree
          :data="rightsTree"
          :props="treeProps"
          node-key="id"
          show-checkbox
          default-expand-all
          :default-checked-keys="defaultCheckedKeys"
          ref="rightsTreeRef"
        ></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
      </el-dialog>
    </template>

    <!-- 添加角色对话框 -->
    <template>
      <el-dialog
        @close="addRolesFormClear"
        title="添加角色"
        :visible.sync="addRolesDialogVisible"
        width="50%"
      >
        <el-form
          :model="addRolesForm"
          :rules="addRolesFormRules"
          ref="addRolesRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
    </template>

    <!-- 编辑角色对话框 -->
    <template>
      <el-dialog
        @close="editRolesFormClear"
        title="编辑角色"
        :visible.sync="editRolesDialogVisible"
        width="50%"
      >
        <el-form
          :model="editRolesForm"
          :rules="editRolesFormRules"
          ref="editRolesRef"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoles">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 分配权限角色的id
      roleId: null,
      // 权限树形结构数据
      rightsTree: [],
      // 树形控件绑定的属性对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 树形结构默认选中的值
      defaultCheckedKeys: [],
      // 是否显示分配权限对话框
      setRightsDialogVisible: false,
      // 是否显示添加角色对话框
      addRolesDialogVisible: false,
      // 添加角色表单数据
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证规则
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      // 是否显示编辑角色对话框
      editRolesDialogVisible: false,
      // 编辑角色表单数据
      editRolesForm: {},
      // 编辑角色表单验证规则
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 删除角色指定权限
    async removeRightsById(role, rightId) {
      console.log(role.id, rightId)
      // 询问用户是否要删除权限
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((error) => error)
      // 确认删除返回字符串confirm,取消删除返回字符串cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除权限')
      }
      // 确认删除权限，发送请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 无需重新加载所有权限，只需更新最新的数据即可
      role.children = res.data
      this.$message.success('删除权限成功')
    },
    // 点击分配权限按钮，触发事件
    async showRightsDialogVisible(role) {
      // 获取权限树形结构数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限树失败')
      }
      this.rightsTree = res.data
      // 展示对话框
      this.setRightsDialogVisible = true
      // 存放所有三级节点的id
      const keys = []
      this.getCheckedKeys(role, keys)
      this.defaultCheckedKeys = keys
      // 将role.id保存起来以供保存权限时使用
      this.roleId = role.id
    },
    // 利用递归函数，获取
    getCheckedKeys(node, keys) {
      // 若无children属性，则为3级节点
      if (!node.children) {
        return keys.push(node.id)
      }
      node.children.forEach((item) => {
        this.getCheckedKeys(item, keys)
      })
    },
    // 分配权限
    async allotRights() {
      // 获取所有选中的节点的key
      const checkedKeys = this.$refs.rightsTreeRef.getCheckedKeys()
      // 获取所有半选中的节点的key
      const halfCheckedKeys = this.$refs.rightsTreeRef.getHalfCheckedKeys()
      // 利用扩展运算符将数组转化成以逗号分隔的参数序列
      const keys = [...checkedKeys, ...halfCheckedKeys]
      // 将数组转换为 , 拼接的字符串
      const idStr = keys.join(',')
      // 发送请求，更新数据
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.eror('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      // 关闭对话框
      this.setRightsDialogVisible = false
    },
    // 关闭分配全向对话框，清空选中项
    setRightsDialogClear() {
      this.defaultCheckedKeys = []
    },
    // 添加角色
    addRoles() {
      this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) return
        // 发送请求
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.getRolesList()
        // 关闭对话框
        this.addRolesDialogVisible = false
      })
    },
    // 关闭添加角色对话框，清空表单
    addRolesFormClear() {
      this.$refs.addRolesRef.resetFields()
    },
    // 点击编辑按钮，显示编辑角色对话框
    showEditRolesDialog(role) {
      this.editRolesForm = role
      this.editRolesDialogVisible = true
    },
    // 编辑角色
    editRoles() {
      this.$refs.editRolesRef.validate(async (valid) => {
        if (!valid) return
        // 发送请求
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesForm.id}`,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑角色失败')
        }
        this.$message.success('编辑角色成功')
        this.getRolesList()
        // 关闭对话框
        this.editRolesDialogVisible = false
      })
    },
    // 关闭编辑角色对话框，清空表单
    editRolesFormClear() {
      this.$refs.editRolesRef.resetFields()
    },
    // 删除角色
    async removeRole(id) {
      // 询问是否要删除该角色
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((error) => error)
      // 如果用户确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除角色')
      }
      // 发送请求，删除角色
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRolesList()
    }
  }
}
</script>

<style lang="less" scoped>
.bdTop {
  border-top: 1px solid #eee;
}

.bdBottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}

.el-tag {
  margin: 7px;
}
</style>
